package com.example.javaproject.spider;

import com.example.javaproject.okhttp.PriorityThreadPool;
import com.example.javaproject.okhttp.SpiderMomentDownloader;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;

public class SpiderMain {
    public static void main(String[] args) {
        File file = new File("E:\\users");
        File[] files = file.listFiles();
        OkHttpProxy.getInstance().init();

        for (File userFile : files) {
            List<FigTxt> figTxts = json2Bean(readContent(userFile));
            for (FigTxt figTxt : figTxts) {
                PriorityThreadPool.getInstance().execute(new SpiderMomentDownloader(figTxt));
            }
        }

        System.out.println();
    }


    public static String readContent(File userFile) {
        try {
            StringBuilder stringBuilder = new StringBuilder();
            BufferedReader bufferedInputStream = new BufferedReader(new InputStreamReader(new FileInputStream(userFile)));
            String len;
            while (null != (len = bufferedInputStream.readLine())) {
                stringBuilder.append(len);
            }
            return stringBuilder.toString();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

    public static List<FigTxt> json2Bean(String content) {
        if (content == null || content.length() == 0) return null;
        Gson gson = new Gson();
        try {
            return gson.fromJson(content, new TypeToken<List<FigTxt>>() {
            }.getType());
        } catch (JsonSyntaxException e) {
            e.printStackTrace();
        }
        return null;
    }
}
